<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realname">
        <el-input
          v-model="queryParams.realname"
          placeholder="请输入真实姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['health:healthUser:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['health:healthUser:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['health:healthUser:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['health:healthUser:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="healthUserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户id" align="center" prop="id" width="150"/>
      <el-table-column label="手机号" align="center" prop="phone" width="120"/>
      <el-table-column label="头像" align="center" prop="avatarUrl">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatarUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="username"/>
      <el-table-column label="真实姓名" align="center" prop="realname"/>
      <el-table-column label="身份证号" align="center" prop="idNum" width="170"/>
      <el-table-column label="详细地址" align="center" prop="address" width="220"/>
      <el-table-column label="注册时间" align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding"
                       fixed="right"
                       width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['health:healthUser:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['health:healthUser:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleResetPassword(scope.row)"
            v-hasPermi="['health:healthUser:edit']"
          >重置密码
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-coordinate"
            @click="showCencernAndFavorite(scope.row)"
            v-hasPermi="['health:healthUser:query']"
          >关注与收藏
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="showFamily(scope.row)"
            v-hasPermi="['health:healthUser:query']"
          >查看家人
          </el-button>
        </template>
      </el-table-column>


    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台用户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" disabled/>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"/>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="form.realname" placeholder="请输入真实姓名"/>
        </el-form-item>

        <el-form-item label="身份证号" prop="idNum">
          <el-input v-model="form.idNum" placeholder="请输入身份证号"/>
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址"/>
        </el-form-item>

        <el-form-item label="头像" prop="avatarUrl">
          <image-upload v-model="form.avatarUrl"
                        :limit="1"
          />

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 【展示“关注与收藏” 的对话框】  -->
    <el-dialog title="关注与收藏" :visible.sync="openTableDialog" width="860">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="关注的养老资源" name="concernTab">
          <!-- 关注表 -->
          <el-table :data="userConcernList" height="500" ref="concernTable" stripe>
            <el-table-column label="ID" width="50" prop="resourceId"/>
            <el-table-column label="名称" width="200" prop="resource.name">
              <template slot-scope="scope">
                <span>{{ scope.row.resource.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="封面图" width="100" align="center" prop="resource.cover">
              <template slot-scope="scope">
                <image-preview :src="scope.row.resource.cover" :width="50" :height="50"/>
              </template>
            </el-table-column>
            <el-table-column label="简介" prop="resource.brief">
              <template slot-scope="scope">
                <div style="
                overflow: hidden;
                display: -webkit-box;
                text-overflow: ellipsis;
                -webkit-line-clamp: 3;
                -webkit-box-orient: vertical;
                white-space: normal;
              ">
                  {{ scope.row.resource.brief }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="收藏的便民服务" name="favoriteTab">
          <!-- 收藏表 -->
          <el-table :data="userFavoriteList" height="500" ref="favoriteTable" stripe>
            <el-table-column label="ID" width="50" prop="serviceId"/>
            <el-table-column label="服务项目" width="200" prop="bmService.serviceItemId">
              <template slot-scope="scope">
                <span>{{ scope.row.bmService.serviceItemId }}</span>
              </template>
            </el-table-column>
            <el-table-column label="封面图" width="100" align="center" prop="bmService.cover">
              <template slot-scope="scope">
                <image-preview :src="scope.row.bmService.cover" :width="50" :height="50"/>
              </template>
            </el-table-column>
            <el-table-column label="地址" prop="resource.address">
              <template slot-scope="scope">
                <div style="
                overflow: hidden;
                display: -webkit-box;
                text-overflow: ellipsis;
                -webkit-line-clamp: 3;
                -webkit-box-orient: vertical;
                white-space: normal;
              ">
                  {{ scope.row.bmService.address }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeTableDialog">关闭</el-button>
      </div>

    </el-dialog>

    <!-- 【展示“家人” 的对话框】  -->
    <el-dialog title="家人列表" :visible.sync="openFamilyDialog" width="1080px">

      <!-- 家人表 -->
      <el-table :data="familyList" height="500"  stripe >
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="家人id" width="80" prop="id"/>
        <el-table-column label="姓名" width="120" prop="realname"></el-table-column>
        <el-table-column label="头像" width="80" align="center" prop="avatarUrl">
          <template slot-scope="scope">
            <image-preview :src="scope.row.avatarUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="身份证照片" width="100" align="center" prop="idImg">
          <template slot-scope="scope">
            <image-preview :src="scope.row.idImg" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="身份证号" width="200" prop="idNum"></el-table-column>
        <el-table-column label="地址" width="200" prop="address"></el-table-column>
        <el-table-column label="备注" prop="remark"></el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeFamilyDialog">关闭</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import {
  listHealthUser,
  getHealthUser,
  delHealthUser,
  addHealthUser,
  updateHealthUser,
  resetPasswordForHealthUser
} from "@/api/health/healthUser";
import {getUserConcernList} from "@/api/health/healthConcern";
import {getUserFavoriteList} from "@/api/health/healthFavorite";
import {listHealthFamily} from "@/api/health/healthFamily";

export default {
  name: "HealthUser",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台用户-表格数据
      healthUserList: [],
      // 我的家人-表格数据
      familyList: [],
      // 用户的收藏列表
      userFavoriteList: [],
      // 用户的关注列表
      userConcernList: [],
      // 弹出层标题
      title: "",
      // 是否显示[修改信息]弹出层
      open: false,
      // tableDialog的标题（关注的养老资源、收藏的便民服务）
      // 是否显示【关注或收藏】弹出层
      openTableDialog: false,
      // 是否显示【家人】弹出层
      openFamilyDialog: false,
      // tab的当前值
      activeTab: 'concernTab',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        phone: null,
        realname: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          {required: true, message: "用户名不能为空", trigger: "blur"}
        ],
        idNum: [
          {required: true, message: '请输入身份证号码', trigger: 'blur'},
          {
            len: 18, message: '中国身份证号码为18位', trigger: 'blur', transform(value) {
              return value.trim()
            }
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询平台用户管理列表 */
    getList() {
      this.loading = true;
      listHealthUser(this.queryParams).then(response => {
        this.healthUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        username: null,
        avatarUrl: null,
        phone: null,
        idNum: null,
        address: null,
        password: null,
        realname: null,
        createTime: null,
        updateTime: null
      };
      // 我的家人
      this.familyList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台用户管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHealthUser(id).then(response => {
        this.form = response.data;
        this.familyList = response.data.familyList;
        this.open = true;
        this.title = "修改平台用户管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.familyList = this.familyList;
          if (this.form.id != null) {
            updateHealthUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHealthUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除平台用户管理编号为"' + ids + '"的数据项？').then(function () {
        return delHealthUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('health/healthUser/export', {
        ...this.queryParams
      }, `healthUser_${new Date().getTime()}.xlsx`)
    },
    //管理员重置User密码为12345678
    handleResetPassword(row) {
      const id = row.id;
      const $model_ = this.$modal
      this.$modal.confirm('是否确认重置ID为"' + id + '"的密码为12345678？').then(function () {
        resetPasswordForHealthUser(id)
          .then(resp => {
            if (resp.code == 200) {
              $model_.msgSuccess("密码重置成功！");
            } else {
              $model_.msgError("密码重置失败！");
            }
          }).catch(() => {
          $model_.msgError("密码重置失败！");
        });
      });
    },
    //查询关注列表
    showCencernAndFavorite(row) {
      const userId = row.id;
      //获取关注
      getUserConcernList(userId).then(resp => {
        if (resp.code == 200) {
          this.userConcernList = resp.rows;
          // 关注的养老资源、收藏的便民服务
        } else {
          this.$message({
            message: '获取用户关注列表失败！',
            type: 'error'
          })
        }
      });
      //获取收藏
      getUserFavoriteList(userId).then(resp => {
        if (resp.code == 200) {
          this.userFavoriteList = resp.rows;
          // 关注的养老资源、收藏的便民服务
          this.openTableDialog = true;
        } else {
          this.$message({
            message: '获取用户收藏列表失败！',
            type: 'error'
          })
        }
      });
    },
    //关闭关注、收藏对话框
    closeTableDialog() {
      this.openTableDialog = false;
      this.userConcernList = [];
      this.userFavoriteList = [];
    },
    //对话框中的tab切换
    handleTabChange(tab, event) {
      // console.log(tab, event);
      // tab切换时，表格会抖动，下面代码可以解决
      // 参考：https://blog.csdn.net/weixin_42331327/article/details/114398125
      this.$nextTick(() => {
        // 页面加载完成后，重新渲染表格
        // forname 为table的ref
        this.$refs['favoriteTable'].doLayout()
        this.$refs['concernTable'].doLayout()
      })
    },
    //获取家人列表
    showFamily(row){
      const userId = row.id;
      listHealthFamily(userId).then(resp=>{
        if (resp.code == 200) {
          this.familyList = resp.rows;
          // 关注的养老资源、收藏的便民服务
          this.openFamilyDialog = true;
        } else {
          this.$message({
            message: '获取用户的家人列表失败！',
            type: 'error'
          })
        }
      })
    },
    closeFamilyDialog(){
      this.openFamilyDialog = false;
      this.familyList = []
    }

  }// end of methods

};
</script>
